#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：sender.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/20 上午12:15 
"""

import logging
from typing import Any

from protocols.tcp_protocol import TCPProtocol
from protocols.udp_protocol import UDPProtocol
from protocols.websocket_protocol import WebSocketProtocol


class Sender:
	def __init__(self, protocol: str, host: str, port: int):
		"""
		初始化发送器。

		:param protocol: 协议类型 ('tcp', 'udp', 'websocket')
		:param host: 目标地址
		:param port: 目标端口
		"""
		self.host = host
		self.port = port
		self.protocol = self._get_protocol(protocol)

	def _get_protocol(self, protocol: str):
		"""根据协议类型返回相应的协议实例"""
		if protocol == 'tcp':
			return TCPProtocol(self.host, self.port)
		elif protocol == 'udp':
			return UDPProtocol(self.host, self.port)
		elif protocol == 'websocket':
			return WebSocketProtocol(self.host, self.port)
		else:
			raise ValueError(f"Unsupported protocol: {protocol}")

	def send(self, data: bytes) -> Any:
		"""
		发送数据。

		:param data: 要发送的数据
		:return: 发送结果
		"""
		try:
			result = self.protocol.send(data)
			logging.info(f"Data sent successfully to {self.host}:{self.port}")
			return result
		except Exception as e:
			logging.error(f"Failed to send data: {e}")
			raise
